import time
from collections import OrderedDict
from datetime import datetime, timedelta
from types import FunctionType

from django.db.models import Sum, Count
from django.http import JsonResponse
from django.shortcuts import render, reverse
from django.utils.safestring import mark_safe

from web import models
from web.utils.pager import Pagernation


def get_total_count(text, field):
    """
    获取choice字段的文本
    :param text: choice字段的名称
    :param field: choice字段
    :return:
    """

    def inner(obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return text
        # date_time = obj.create_datetime
        # fatal_count = models.SangforFwAttackLog.objects.filter(create_datetime__year=date_time.year,
        #                                                        create_datetime__month=date_time.month,
        #                                                        create_datetime__day=date_time.day,
        #                                                        level=0).count()
        record_url = reverse('skyeyelog_list', kwargs={'pk': obj.id})
        tpl = '<a class="btn btn-info" href="{}">{:,}</a>'.format(record_url, obj.total)
        return mark_safe(tpl)

    return inner


def get_attackip_count(text, field):
    """
    获取choice字段的文本
    :param text: choice字段的名称
    :param field: choice字段
    :return:
    """

    def inner(obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return text
        date_time = obj.create_datetime
        attackip_count = models.SkyEyeLog.objects.filter(create_datetime__year=date_time.year,
                                                         create_datetime__month=date_time.month,
                                                         create_datetime__day=date_time.day,
                                                         ).exclude(attack_sip='').values('attack_sip').annotate(
            ct=Count('attack_sip')).count()
        record_url = reverse('skyeye_attackip_list', kwargs={'pk': obj.id})
        tpl = '<a class="btn btn-info" href="{}">{:,}</a>'.format(record_url, attackip_count)
        return mark_safe(tpl)

    return inner


def skyeye_list(request):
    list_display = [
        'cnt_fatal',
        'cnt_high',
        'cnt_mid',
        'cnt_low',
        get_total_count('合计', 'total'),
        get_attackip_count('攻击IP数', 'total'),
        'update_datetime'
    ]
    queryset = models.SkyEye.objects.all().order_by('-update_datetime')
    model_class = models.SkyEye
    pager = Pagernation(request, queryset)
    # 1.处理表头
    header_list = []
    if list_display:
        for key_or_func in list_display:
            if isinstance(key_or_func, FunctionType):
                header_list.append(key_or_func(None, True))
            else:
                verbose_name = model_class._meta.get_field(key_or_func).verbose_name
                header_list.append(verbose_name)
    else:
        header_list.append(model_class._meta.model_name)
    # 2.处理表格内容
    data_list = queryset[pager.start:pager.end]
    body_list = []
    for row in data_list:
        tr_list = []
        if list_display:
            for key_or_func in list_display:
                if isinstance(key_or_func, FunctionType):
                    tr_list.append(key_or_func(row, False))
                else:
                    tr_list.append('' if getattr(row, key_or_func) == None else getattr(row, key_or_func))
        else:
            tr_list.append(row)
        body_list.append(tr_list)

    context = {
        'body_list': body_list,
        'header_list': header_list,
        'pager': pager,
    }
    return render(request, 'skyeye_list.html', context)


def get_data_dict(field, field_name):
    today = datetime.now().date() + timedelta(days=1)
    date_dict = OrderedDict()
    for i in range(0, 30):
        date = today - timedelta(days=i)
        date_dict[date.strftime("%Y-%m-%d")] = [time.mktime(date.timetuple()) * 1000, 0]

    queryset = models.SkyEye.objects.filter(create_datetime__gt=today - timedelta(days=29)).extra(
        select={'ctime': "DATE_FORMAT(web_skyeye.create_datetime,'%%Y-%%m-%%d')"}).values('ctime').annotate(
        ct=Sum(field))
    for item in queryset:
        date_dict[item['ctime']][1] = item['ct']
    return {'name': field_name, 'data': list(date_dict.values())}


def skyeye_account_chart(request):
    account_mapping = {'total': '告警总数',
                       'cnt_fatal': '危急',
                       'cnt_high': '高危',
                       'cnt_mid': '中危',
                       'cnt_low': '低危'
                       }
    data_list = []
    for k, v in account_mapping.items():
        data_list.append(get_data_dict(k, v))
    return JsonResponse({'status': True, 'data': data_list})
